package com.connor.chint.sap2.assignfactoryno;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.Map.Entry;

import javax.swing.JTextField;

import org.apache.commons.collections.map.HashedMap;

import com.connor.chint.sap2.bean.FactoryNoBean;
import com.connor.chint.sap2.bean.FlowNoBean;
import com.connor.chint.sap2.bombuilder.BomBuildDialogController;
import com.connor.chint.sap2.sap_zy.FlowBean;
import com.connor.chint.sap2.util.ChintPreferenceUtil;
import com.connor.chint.sap2.util.KUtil;
import com.connor.chint.sap2.util.POIUtil;
import com.connor.chint.sap2.util.ProgressBar;
import com.connor.chint.sap2.util.SqlUtil;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentContextList;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

import plm.xi.com.chintelectric.DT_FACTORY_NUMBER_REQ;
import plm.xi.com.chintelectric.DT_FACTORY_NUMBER_REQBASEINFO;
import plm.xi.com.chintelectric.DT_FACTORY_NUMBER_REQITEMSITEM;
import plm.xi.com.chintelectric.DT_FACTORY_NUMBER_RSP;
import plm.xi.com.chintelectric.DT_FACTORY_NUMBER_RSPRSP_BASEINFO;
import plm.xi.com.chintelectric.DT_FACTORY_NUMBER_RSPZTABLE_RETURN;
import plm.xi.com.chintelectric.SI_FACTORY_NUMBER_PLM_OUT_SYN;
import plm.xi.com.chintelectric.SI_FACTORY_NUMBER_PLM_OUT_SYNService;
import plm.xi.com.chintelectric.SI_FACTORY_NUMBER_PLM_OUT_SYNServiceLocator;

public class FactoryCCController {

	private FactoryCCDialog dialog;
	private AbstractAIFApplication app;
	
	private List<String> factoryNos = new ArrayList<>();
	
	
	public FactoryCCController(AbstractAIFApplication app,FactoryCCDialog dialog) {
		// TODO Auto-generated constructor stub
		this.dialog = dialog;
		this.app = app;
	}
	
	//ȡƷͺŶӦǰ׺
	public Map<String, String> getFactoryTypes(String preference,TCSession session)
	{
		Map<String, String> map = new HashedMap(16);
		String[] prefs = ChintPreferenceUtil.getPreferences(preference, session);
		String[] values = null;
		String[] types = null;
		String value = "";
		for(int i=0,len = prefs.length;i<len;i++)
		{
			values = prefs[i].split(":");
			if(values.length!=2)
				continue;
			value = values[0];
			types = values[1].split(";");			
			for(int j=0,len2 = types.length;j<len2;j++)
			{
				map.put(types[j], value);
			}			
		}
		//System.out.println("map:"+map);
		return map;
	}
	
	public List<FactoryNoBean> getCCPList(TCComponent ccp_Folder,Map<String, String> map,
			Map<String, FlowNoBean> map_FlowNos) throws Exception
	{
		List<FactoryNoBean> list = new ArrayList<>(32);
		AIFComponentContext[] childs = ccp_Folder.getChildren();
		TCComponent[] contexts = null;
		FactoryNoBean bean = null;
		int index = 1;
		String zt2_Site = "";
		String zt2_MaterialNo ="";
		String object_name = "";
		String prefix = "";
		String zt2_TankNo ="";
		List<TCComponent> factoryNos = null;	//Ŷ󼯺
		List<String> factoryIDs = null;		//ID
		TCComponentItemRevision rev = null;
		List<String> types = new ArrayList<>(map.keySet());
		String type = "";
		String factoryID = "";
		String flowNo ="";				
		FlowNoBean flowBean = null;
		String time = new Date().getYear()%100 + String.format("%02d",new Date().getMonth()+1);
		String temp = "";
		for(int i=0,len = childs.length;i<len;i++)
		{
			flowNo = "";
			temp ="";
			if(childs[i].getComponent().getType().equals("Part"))
			{
				rev = ((TCComponentItem)childs[i].getComponent()).getLatestItemRevision();
				zt2_Site = rev.getProperty("zt2_Site");
				zt2_MaterialNo = rev.getProperty("zt2_MaterialNo");
				object_name = rev.getProperty("object_name");
				zt2_TankNo = rev.getProperty("zt2_TankNo");
				type = KUtil.inArray2(object_name, types);
				if(!KUtil.isEmpty(type))
				{
					prefix = map.get(type);
					System.out.println("prefix:"+prefix);
					if(map_FlowNos.containsKey(prefix))
					{
						flowBean = map_FlowNos.get(prefix);
						flowBean.addSize();;
					}else
					{
						flowBean = new FlowNoBean(prefix);
						map_FlowNos.put(prefix, flowBean);
					}
					contexts = rev.getRelatedComponents("ZT2_FactoryNumber");
					if(contexts.length>0)
					{
						factoryID = contexts[0].getProperty("item_id");
						temp = factoryID;
						flowNo = factoryID.substring(factoryID.length()-4, factoryID.length());
						temp = temp.substring(factoryID.length()-8, factoryID.length()-4);
						prefix = factoryID.replaceAll(temp, "").replaceAll(flowNo, "");
						flowBean.addIDs(factoryID);	
					}else 
					{
						if(prefix.endsWith("DX"))
						dialog.isHave = true;
						temp = time;
					}
					
					
					
					
					
					if(contexts.length>0 && contexts[0].getProperty("item_id").contains(prefix))
					{
						factoryID = contexts[0].getProperty("item_id");
						temp = factoryID.replaceAll(prefix, "");
						temp = temp.substring(temp.length()-8, temp.length()-4);
						flowNo = factoryID.substring(factoryID.length()-4, factoryID.length());
						flowBean.addIDs(factoryID);
					}else
					{
						temp = time;
					}
				}else
				{
					
					throw new Exception("Ʒ["+rev+"]δƥŹ");
				}
			}	
			System.out.println("rev:"+rev+";flowNo:"+flowNo);
			factoryNos = new ArrayList<>(8);
			factoryIDs = new ArrayList<>(8);
			bean = new FactoryNoBean(rev, factoryNos, factoryIDs, 
					zt2_MaterialNo, object_name, zt2_Site, zt2_TankNo,
					"", i+1, prefix, flowNo);
			bean.time = temp;
			list.add(bean);
		}
		System.out.println("map_FlowNos:"+map_FlowNos);
		return list;
	}
	
	private Map<String, TCComponentItemRevision> factoryNo_Products = new HashedMap();
	public List<FactoryNoBean> getCCPList2(TCComponent ccp_Folder,Map<String, String> map,
			Map<String, FlowNoBean> map_FlowNos) throws Exception
	{
		List<FactoryNoBean> list = new ArrayList<>(32);
		AIFComponentContext[] childs = ccp_Folder.getChildren();
		TCComponent[] contexts = null;
		FactoryNoBean bean = null;
		int index = 1;
		String zt2_Site = "";
		String zt2_MaterialNo ="";
		String object_name = "";
		String prefix = "";
		String zt2_TankNo ="";
		List<TCComponent> factoryNos = null;	//Ŷ󼯺
		List<String> factoryIDs = null;		//ID
		TCComponentItemRevision rev = null;
		List<String> types = new ArrayList<>(map.keySet());
		String type = "";
		String factoryID = "";
		String flowNo ="";				
		FlowNoBean flowBean = null;
		String time = new Date().getYear()%100 + String.format("%02d",new Date().getMonth()+1);
		String temp = "";
		String zt2_Quantity = "";
		TCComponent[] factorys;
		int[] indexs;
		for(int i=0,len = childs.length;i<len;i++)
		{
			flowNo = "";
			temp ="";
			if(childs[i].getComponent().getType().equals("Part"))
			{
				rev = ((TCComponentItem)childs[i].getComponent()).getLatestItemRevision();
				zt2_Site = rev.getProperty("zt2_Site");
				zt2_MaterialNo = rev.getProperty("zt2_MaterialNo");
				object_name = rev.getProperty("object_name");
				zt2_TankNo = rev.getProperty("zt2_TankNo");
				type = KUtil.inArray2(object_name, types);
				zt2_Quantity = rev.getStringProperty("zt2_Quantity");
				if (KUtil.isEmpty(zt2_Quantity)) {
					zt2_Quantity = "1";
					indexs = new int[] { 1 };
				} else {
					int size = POIUtil.getIntValue(zt2_Quantity)==0?1:POIUtil.getIntValue(zt2_Quantity);
					indexs = new int[size];
				}
				
				factorys = rev.getRelatedComponents(BomBuildDialogController.REL_FACTORYNO);
				factoryNos = new ArrayList<>();
				factoryIDs = new ArrayList<String>();
				//ZT2_FactoryNumber
				if (factorys != null && factorys.length > 0) {

					for (int j = 0; j < factorys.length; j++) {
						factoryID = factorys[j].getProperty("item_id");
						factoryNos.add(factorys[j]);
						factoryIDs.add(factoryID);
						factoryNo_Products.put(factoryID, rev);
					}
					//isHaveFactoryNo = true;
				}else
				{
					if(!KUtil.isEmpty(type))
					{
						prefix = map.get(type);

						
					}else
					{
						throw new Exception("Ʒ"+rev+"δƥŷ");
					}
				}
				
				
				
				
				
				
				
				
			}	
		}
		if (list.size() > 0) {
			Collections.sort(list, new Comparator<FactoryNoBean>() {

				@Override
				public int compare(FactoryNoBean o1, FactoryNoBean o2) {
					// TODO Auto-generated method stub
					return o1.getZt2_MaterialNo().compareTo(o2.getZt2_MaterialNo());
				}
			});
		}
		
		
		
		
		
		return list;
	}
	/**
	 * ǰ׺ˮ
	 * DX⴦
	 * @param beans
	 * @param session
	 * @throws Exception
	 */
	public void getFlowNo(Map<String, FlowNoBean> beans,TCSession session) throws Exception 
	{
		String[] prefs = ChintPreferenceUtil.getPreferences("database_tc", session);
		if(SqlUtil.getTCDataConnection(prefs)==null)
		{
			throw new Exception("޷ݿ,ѡ<database_tc>á");
		}
	
		String time = new Date().getYear()%100 + String.format("%02d",new Date().getMonth()+1);
		FlowNoBean bean = null;
		FlowNoBean clone = null;
		if(beans.containsKey("DX"))
		{
			System.out.println("");
			bean = beans.get("DX");
			clone = (FlowNoBean) bean.clone();
			clone.setPrefix("DX1");
			beans.put("DX1", clone);
			clone = (FlowNoBean) bean.clone();
			clone.setPrefix("DX3");
			beans.put("DX3", clone);
			beans.remove("DX");
		}
		
		List<String> types = new ArrayList<>(beans.keySet());
		
		StringBuffer buff = new StringBuffer(64);
		buff.append("(");
		int len = types.size();
		for(int i=0;i<len-1;i++)
		{
			buff.append("?").append(",");
		}
		buff.append("?").append(")");
		types.add(time);
		String sql = "select type,time,flow from \"CHINT_M008_FactoryNo\" where 1=1 ";
		sql+=" and type in "+buff.toString() +" and time = ?";
		System.out.println("sql:"+sql);
		ResultSet rs = SqlUtil.read(sql,types.toArray(new Object[types.size()]));
		String type = "";
		String flow = "";
		while(rs.next())
		{
			type = rs.getString(1);
			flow = rs.getString(3);
			bean = beans.get(type);
			bean.isInsert = false;
			bean.setStart(POIUtil.getIntValue(flow));
		}
		SqlUtil.free();
		System.out.println("beans:"+beans);
	}
	
	public void autoAssign(Map<String, FlowNoBean> beans)
	{
		factoryNos.clear();
		int rowCount = dialog.t_bom.getRowCount();
		FactoryNoBean bean = null;
		FlowNoBean flowBean = null;
		String type = "";
		int flow = 0;
		System.out.println("beans:"+beans);
		String item_id = "";
		for(int i=0;i<rowCount;i++)
		{
			bean = (FactoryNoBean) dialog.t_bom.getValueAt(i, 3);
			String val =  (String) dialog.t_bom.getValueAt(i, 6);
			if(KUtil.isEmpty(val))
			{
				type  = bean.getPrefix();
				System.out.println("type:"+type);
				flowBean = beans.get(type);
				flow = flowBean.getStart();
				flowBean.setStart(flow+1);
				
				dialog.t_bom.setValueAt(bean.getPrefix()+bean.time, i, 5);		
				dialog.t_bom.setValueAt(String.format("%04d", flow), i, 6);
				item_id = bean.getPrefix()+bean.time+String.format("%04d", flow);
				flowBean.addIDs(item_id);
			}else
			{
				item_id = bean.getPrefix()+bean.time+val;
			}
			factoryNos.add(item_id);
		}
	}
	
	
	public void assign(Map<String, FlowNoBean> beans,TCSession session,TCComponent ccbh_Folder) throws Exception
	{
		int rowCount = dialog.t_bom.getRowCount();
		FactoryNoBean bean = null;
		FlowNoBean flowBean = null;
		Map<String, TCComponent> maps = new HashedMap(16);
		StringBuffer buff = new StringBuffer();
		String item_id = "";
		String prefix = "";
		
		
		
		for(int i=0;i<rowCount;i++)
		{
			bean = (FactoryNoBean) dialog.t_bom.getValueAt(i, 3);
			String val =  (String) dialog.t_bom.getValueAt(i, 6);
			if(KUtil.isEmpty(val))
			{
				buff.append(""+(i+1)+"δ");
				continue;
			}
			
			item_id = bean.getPrefix()+bean.time+val;
			if(maps.containsKey(item_id))
			{
				buff.append(""+(i+1)+"ظ");
				continue;
			}
			maps.put(item_id, null);
			if(!factoryNos.contains(item_id))
			{
				prefix = bean.getPrefix();
				flowBean = beans.get(prefix);
				if(!flowBean.getIds().contains(item_id))
				{
					buff.append(""+(i+1)+"гŲڿɷ䷶Χ");
					continue;
				}
			}		
		}
		if(buff.toString().length()>0)
		{
			throw new Exception(buff.toString());
		}
		for(String id:maps.keySet())
		{
			TCComponent[] items = session.search(" ID", new String[] { " ID" }, new String[] { id });
			if (items == null || items.length == 0) {
				TCComponentItem item = KUtil.newItem(session, BomBuildDialogController.TYPE_FACTORYNO, id, "");
				ccbh_Folder.add("contents", item);
				maps.put(id, item);
			}else
			{
				maps.put(id, items[0]);
			}
		}
		String type="";
		String flowNo = "";
		String sql_update = "update \"CHINT_M008_FactoryNo\" set flow =? where type =? and time = ?";
		String sql_insert = "insert into \"CHINT_M008_FactoryNo\"(flow,type,time) values(?,?,?) ";
		Object[] obj = new Object[3];
		String time = new Date().getYear()%100 + String.format("%02d",new Date().getMonth()+1);
		TCComponentItemRevision rev = null;
		
		for(int i=0;i<rowCount;i++)
		{
			bean = (FactoryNoBean) dialog.t_bom.getValueAt(i, 3);
			String val =  (String) dialog.t_bom.getValueAt(i, 6);
			item_id = bean.getPrefix()+bean.time+val;
			rev = bean.getRev();
			TCComponent[] comps = rev.getRelatedComponents(BomBuildDialogController.REL_FACTORYNO);
			rev.cutOperation(BomBuildDialogController.REL_FACTORYNO, comps);
			rev.add(BomBuildDialogController.REL_FACTORYNO, maps.get(item_id));			
		}
		

		
		for(String key:beans.keySet())
		{			
			flowBean = beans.get(key);
			type = key;
			flowNo = flowBean.getStart()+"";
			obj[0] = flowNo;
			obj[1] = type;
			obj[2] = time;
			if(flowBean.isInsert)
			{
				SqlUtil.write(obj, sql_insert);
			}else
			{
				SqlUtil.write(obj, sql_update);
			}
			SqlUtil.free();
		}
		
		MessageBox.post("ŷ","",2);
	}
	
	
	
	
}
